<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="utf-8">
	<base href="http://localhost/notebook/php_advanced_and_object_oriented_programming_visual_quickpro_guide/" />
	<title>添加任务</title>
	<link rel="stylesheet" href="../css/bootstrap.css">
</head>
<body>
<?php
/**
 * Created by PhpStorm.
 * User: ford
 * Date: 14-9-16
 * Time: 下午4:47
 */

$dbc = mysqli_connect('localhost', 'root', 'al8840dd', 'test');

if(($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['task'])) {
	//检查输入...

	//ID必须是整数，
	if (isset($_POST['parent_id']) &&
		filter_var($_POST['parent_id'], FILTER_VALIDATE_INT, array('min_range' => 1))) {	//使用过滤扩展确保所接收的值为整数
		$parent_id = $_POST['parent_id'];
	} else {
		$parent_id = 0;
	}

	//转义输入字符，将接收到的字符改为转义字符，这样可以防止跨站脚本注入攻击，strip_tags()函数也同时用于检查描述任务的字符串
	$task = mysqli_real_escape_string($dbc, strip_tags($_POST['task']));

	//添加任务到数据库中
	$q = "INSERT INTO tasks(parent_id, task) VALUES($parent_id, '$task')";
	$r = mysqli_query($dbc, $q);

	//显示结果
	if (mysqli_affected_rows($dbc) == 1) {
		echo '<p>任务已添加！</p>';
	} else {
		echo '<p>任务添加失败！</p>';
	}
}

	//显示输入表单
	echo '
	<form action="./add_task.php" method = "post">
		<fieldset>
			<legend>添加任务</legend>
			<label>任务名称：<input name="task" type="text" size="60" maxlength="100" required /></label>
			<br />
			<label>上级任务：
				<select name="parent_id">
					<option value="0">-无-</option>
	';
	//查询所有未完成任务
	$q = 'SELECT task_id, parent_id, task FROM tasks WHERE date_completed="0000-00-00 00:00:00" ORDER BY date_added ASC';
	$r = mysqli_query($dbc, $q);

	//定义任务数组
	$tasks = array();

	//读取记录
	while (list ($task_id, $parent_id,$task) = mysqli_fetch_array($r, MYSQLI_NUM)) {
		//添加到SELECT元素中
		echo "<option value=\"$task_id\">$task</option>\n";

		//添加到数组中
		$tasks[] = array('task_id'=>$task_id, 'parent_id'=>$parent_id, 'task'=>$task);
	}

	//结束表单
	echo '
		</select>
		</label>
		<input name="submit" type="submit" value="添加新任务">
		</fieldset>
		</form>
		';

	//定义排序函数，降序
	function parent_sort($x, $y) {
		return ($x['parent_id'] > $y['parent_id']);
	}

	usort($tasks, 'parent_sort');

	//显示所有任务
	echo '<h2>当前任务列表</h2><ul>';
	foreach($tasks as $task) {
		echo "<li>{$task['task']}</li>\n";
	}
	echo '</ul>';
//	var_dump($tasks);
?>
</body>
</html>